package com.unitd.base.frame.plugin.aliyun;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.unitd.base.frame.enums.ResultEnum;
import com.unitd.base.frame.exception.UnitdException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

/**
 * 阿里云短信接口配置类
 *
 * @author hudan
 * @version 1.0
 * @filename AliyunSmsConfig.java
 * @copyright www.symdata.cn
 * @date 2019/11/15
 */
@SpringBootConfiguration
@EnableConfigurationProperties(AliyunSmsProperties.class)
@Slf4j
public class AliyunSmsConfiguration {

    @Autowired
    private AliyunSmsProperties aliyunSmsProperties;

    /**
     * 短信发送
     *
     * @param phone    需要发送的手机号码
     * @param verifyNo 短信验证码
     * @return 阿里云反馈结果
     */
    public SendSmsResponse sendSms(String phone, String verifyNo) {

        try {
            /* 超时时间，可自主调整 */
            System.setProperty("sun.net.client.defaultConnectTimeout", aliyunSmsProperties.getConnectTimeout());
            System.setProperty("sun.net.client.defaultReadTimeout", aliyunSmsProperties.getReadTimeout());

            /* 初始化acsClient,暂不支持region化 */
            IClientProfile profile = DefaultProfile.getProfile(aliyunSmsProperties.getRegionId(), aliyunSmsProperties.getAccessKey(), aliyunSmsProperties.getAccessSecret());
            DefaultProfile.addEndpoint(aliyunSmsProperties.getEndpointName(), aliyunSmsProperties.getRegionId(), aliyunSmsProperties.getProduct(), aliyunSmsProperties.getDomain());
            IAcsClient acsClient = new DefaultAcsClient(profile);

            /* 组装请求对象-具体描述见控制台-文档部分内容 */
            SendSmsRequest request = new SendSmsRequest();
            // 必填:待发送手机号
            request.setPhoneNumbers(phone);
            // 必填:短信签名-可在短信控制台中找到
            request.setSignName(aliyunSmsProperties.getSignName());
            // 必填:短信模板code-可在短信控制台中找到
            request.setTemplateCode(aliyunSmsProperties.getTemplateCode());
            // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的用户,您的验证码为${no}"时,此处的值为
            request.setTemplateParam("{\"no\":\"" + verifyNo + "\"}");

            // hint 此处可能会抛出异常，注意catch
            return acsClient.getAcsResponse(request);
        } catch (Exception e) {
            log.error("短信发送失败![{}]", e.getMessage());
            throw new UnitdException(ResultEnum.FAIL);
        }
    }
}